package com.imu.aop.aop;

import com.imu.aop.entity.LoginInfo;
import com.imu.aop.entity.User;
import com.imu.aop.service.ILoginInfoService;
import com.imu.aop.utils.IpUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Component
@Aspect
public class AopAdvice {

    @Autowired
    ILoginInfoService iLoginInfoService;
    @Pointcut("execution (* com.imu.aop.controller.UserController.*(..))")
    public void log() {

    }

    @AfterReturning(returning = "res",pointcut = "log()")
    public void afterReturning(Object res){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        String ipAddr = IpUtil.getIpAddr(request);

        LoginInfo loginInfo = new LoginInfo();
        User user = (User) res;
        loginInfo.setId(user.getId());
        loginInfo.setIp( ipAddr);
        loginInfo.setName(user.getUsername());

        Date date = new Date();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = date.toInstant().atZone(zoneId).toLocalDateTime();

        loginInfo.setTime(localDateTime);

        iLoginInfoService.save(loginInfo);
        System.out.println(ipAddr);
        System.out.println("--------------------------");
        System.out.println(res);
    }

}
